class_name JumpAbility
extends GameplayAbility

var _jumped: bool = false

var _can_jump: bool = false

#region 跳跃缓冲
var _jump_buffer_time: float = 0.2

var _jump_buffer_timer: float = 0.0
#endregion

#region 土狼跳跃
var _coyote_time: float = 0.2

var _coyote_timer: float = 0.0

var _coyote_once_triggered: bool = false
#endregion


func _on_owner_set() -> void:
	pass


func _can_apply() -> bool:
	if not _jumped and _can_jump:
		_jumped = true
		return true
	else:
		return false


func _on_update(delta: float) -> void:
	var is_on_ground = owner.tag_manager.has_tag(GameplayTagLibrary.State_Ground)
	
	if is_on_ground:
		_jumped = false
		_can_jump = true
	else:
		_can_jump = false

	#region 跳跃缓冲
	if not is_on_ground:
		if owner.input_handler.is_action_just_pressed("jump"):
			# 当不在地面时，如果按下跳跃键，则设置跳跃缓冲计时器
			_jump_buffer_timer = _jump_buffer_time
		# 更新跳跃缓冲计时器
		_jump_buffer_timer -= delta

	# 如果跳跃缓冲计时器大于0，则可以跳跃
	if is_on_ground and _jump_buffer_timer > 0:
		_jump_buffer_timer = 0
		owner.ability_manager.try_apply_ability(ability_asset, owner)
	#endregion

	#region 土狼跳跃
	# 当没有跳跃过，且不在地面，则处理土狼跳跃（排除墙跳）
	if not _jumped and not is_on_ground:
		# 设置土狼跳跃计时器
		if not _coyote_once_triggered:
			_coyote_once_triggered = true
			_coyote_timer = _coyote_time
		# 土狼跳跃计时器大于0，则可以跳跃
		_can_jump = _coyote_timer > 0
		# 更新土狼跳跃计时器
		_coyote_timer -= delta
	#endregion


func _create_spec() -> GameplayAbilitySpec:
	return JumpAbilitySpec.new(self)
